
<template>
  <a-row :gutter="16" class="height100">
    <a-col :span="6">
      <a-card style="height: 100%">
        <orgTreeSelection ref="orgTreeSelectionRef" @change="deviceSelect"/>
      </a-card>
    </a-col>

    <a-col :span="18" class="height100">
      <div class="employee-box height100">
        <!---------- 查询表单form begin ----------->
        <a-form class="smart-query-form">
          <a-row class="smart-query-form-row">
            <a-form-item label="设备名称" class="smart-query-form-item">
              <a-input style="width: 150px" v-model:value="queryForm.stationName" placeholder="设备名称" />
            </a-form-item>
            <a-form-item label="设备类型" class="smart-query-form-item">
              <!-- <DictSelect width="100%" style="width: 150px" v-model:value="queryForm.deviceType" keyCode="device_type" placeholder="设备类型" /> -->
              <a-select  style="width: 150px" v-model:value="queryForm.deviceType" placeholder="设备类型" >
                <a-select-option v-for="item in dictValueList" :key="item.valuecode" :value="item.valueCode">{{ item.valueName }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="SN" class="smart-query-form-item">
              <a-input style="width: 150px" v-model:value="queryForm.snCode" placeholder="SN" />
            </a-form-item>
            <a-form-item class="smart-query-form-item">
              <a-button type="primary" @click="queryData">
                <template #icon>
                  <SearchOutlined />
                </template>
                查询
              </a-button>
              <a-button @click="resetQuery" class="smart-margin-left10">
                <template #icon>
                  <ReloadOutlined />
                </template>
                重置
              </a-button>
            </a-form-item>
          </a-row>
        </a-form>
        <!---------- 查询表单form end ----------->

        <a-card size="small" :bordered="false" :hoverable="true">
          <!---------- 表格操作行 begin ----------->
          <a-row class="smart-table-btn-block">
            <div class="smart-table-operate-block">
              <a-button @click="showForm" type="primary" size="small">
                <template #icon>
                  <PlusOutlined />
                </template>
                新建
              </a-button>
              <a-button @click="confirmBatchDelete" type="danger" size="small" :disabled="selectedRowKeyList.length == 0">
                <template #icon>
                  <DeleteOutlined />
                </template>
                批量删除
              </a-button>
            </div>
            <div class="smart-table-setting-block">
              <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.DEVICE.PUMPGATE" :refresh="queryData" />
            </div>
          </a-row>
          <!---------- 表格操作行 end ----------->

          <!---------- 表格 begin ----------->
          <a-table
            size="small"
            :dataSource="tableData"
            :columns="columns"
            rowKey="deviceId"
            bordered
            :loading="tableLoading"
            :pagination="false"
            :scroll="{ x: 2000 }"
            :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
          >
            <template #bodyCell="{ text, record, column }">
              <template v-if="column.dataIndex === 'deviceType'">
                <span>{{ getDictName(dictValueList, text) }}</span>
              </template>

              <template v-if="column.dataIndex === 'usageStatus'">
                <span>{{ getDictName(usageStatusDictValueList, text) }}</span>
              </template>
              <template v-if="column.dataIndex === 'runningStatus'">
                <a-tag v-if="text != null && text != 'offline'" color="#87d068">{{ getDictName(deviceRunningStatusDictValueList, text) }} </a-tag>
                <a-tag v-else color="default">离线</a-tag>
              </template>

              <template v-if="column.dataIndex === 'action'">
                <div class="smart-table-operate">
                  <a-button @click="showDeviceRunningLog(record)" type="link">运行日志</a-button>
                  <a-button @click="showForm(record)" type="link">编辑</a-button>
                  <a-button @click="onDelete(record)" danger type="link">删除</a-button>
                </div>
              </template>
            </template>
          </a-table>
          <!---------- 表格 end ----------->

          <div class="smart-query-table-page">
            <a-pagination
              showSizeChanger
              showQuickJumper
              show-less-items
              :pageSizeOptions="PAGE_SIZE_OPTIONS"
              :defaultPageSize="queryForm.pageSize"
              v-model:current="queryForm.pageNum"
              v-model:pageSize="queryForm.pageSize"
              :total="total"
              @change="queryData"
              @showSizeChange="queryData"
              :show-total="(total) => `共${total}条`"
            />
          </div>
          <!-- 新增、编辑表单 deviceDict：设备类型字典值； deviceTypeIsdisabled： 设备类型是否禁用，   -->
          <DeviceForm ref="formRef" :deviceDict="dictValueList" :deviceTypeIsdisabled="false"  @reloadList="queryData" />
          <devicePumpGateLog ref="deviceRunningLogRef" />
        </a-card>
      </div>
    </a-col>
  </a-row>
</template>
<script setup>
import { reactive, ref, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { SmartLoading } from '/@/components/framework/smart-loading';
import { deviceApi } from '/@/api/main/basic/device-api';
import {PAGE_SIZE, PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';
import { smartSentry } from '/@/lib/smart-sentry';
import TableOperator from '/@/components/support/table-operator/index.vue';
import DeviceForm from '../device-form.vue';
import { getDictName } from "/@/utils/tool.js"
import orgTreeSelection from '/@/components/main/org-tree-selection.vue';
import { dictApi } from '/src/api/support/dict-api';
import devicePumpGateLog from '../device-pump-gate-log.vue';
// ---------------------------- 数据初始化 ----------------------------
// 获取设备类型
const dictValueList = ref([]);
const usageStatusDictValueList = ref([]);
const deviceRunningStatusDictValueList = ref([])
// 查询字典值
async function queryDict() {
    // 获取设备类型字典
    dictValueList.value = []
    let res = await dictApi.valueList('device_type');
     res.data.forEach(item => {
      if(item.valueCode == '0'|| item.valueCode == '2' || item.valueCode == '4'){
        dictValueList.value.push(item)
      }
    });

    // 获取设备使用状态字典
    let obj = await dictApi.valueList('device_usage_status');
    usageStatusDictValueList.value = obj.data;

    // 获取设备运行状态字典值

    let runningStatusList = await dictApi.valueList('device_running_status');
    deviceRunningStatusDictValueList.value = runningStatusList.data;
  }
// 初始化机构树
const orgTreeSelectionRef = ref()



// 表头
const columns = ref([
    {
      title: '设备名称',
      dataIndex: 'deviceName',
      fixed: 'left',
      align: 'center',
      width: 200,
      ellipsis: true,
    },

    {
      title: '设备类型',
      dataIndex: 'deviceType',
      fixed: 'left',
      align: 'center',
      width: 120,
      ellipsis: true,
    },
    {
      title: 'SN号',
      dataIndex: 'snCode',
      fixed: 'left',
      align: 'center',
      width: 120,
      ellipsis: true,
    },
    {
      title: '运行状态',
      dataIndex: 'runningStatus',
      fixed: 'left',
      align: 'center',
      width: 120,
      ellipsis: true,
    },
    {
      title: '所属支门泵站',
      dataIndex: 'stationName',
      align: 'center',
      width: 200,
      ellipsis: true,
    },
    {
      title: '物联网卡号',
      dataIndex: 'cardNum',
      align: 'center',
      width: 120,
      ellipsis: true,
    },


    {
      title: '设备坐标',
      dataIndex: 'coordinate',
      align: 'center',
      width: 120,
      ellipsis: true,
    },
    {
      title: '制造商',
      dataIndex: 'manufacturer',
      align: 'center',
      width: 120,
      ellipsis: true,
    },
    {
      title: '型号',
      dataIndex: 'model',
      align: 'center',
      width: 120,
      ellipsis: true,
    },
    {
      title: '购买日期',
      dataIndex: 'purchaseDate',
      align: 'center',
      width: 120,
      ellipsis: true,
    },
    {
      title: '保修到期日期',
      dataIndex: 'warrantyExpiryDate',
      align: 'center',
      width: 120,
      ellipsis: true,
    },
    {
      title: '设备状态',
      dataIndex: 'usageStatus',
      align: 'center',
      width: 120,
      ellipsis: true,
    },
    {
      title: '备注信息',
      dataIndex: 'notes',
      align: 'center',
      width: 200,
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      fixed: 'right',
      width: 160,
    },
  ]);

// ---------------------------- 查询数据表单和方法 ----------------------------

const queryFormState = {
  stationName: undefined, //设备名称
  deviceType: undefined, //设备类型（见系统字典表）
  deviceTypeList: undefined, //设备类型（见系统字典表）
  snCode: undefined, //SN
  areaId: undefined, //所属区域
  managementStationId: undefined, //所属管理所
  stationId: undefined, //所属支门泵站
  pageNum: 1,
  pageSize: PAGE_SIZE,
};
// 查询表单form
const queryForm = reactive({ ...queryFormState });
// 表格加载loading
const tableLoading = ref(false);
// 表格数据
const tableData = ref([]);
// 总数
const total = ref(0);

// 重置查询条件
function resetQuery() {
  orgTreeSelectionRef.value.resetValue()
  let pageSize = queryForm.pageSize;
  Object.assign(queryForm, queryFormState);
  queryForm.pageSize = pageSize;
  queryData();
}
// 点击左侧树
function deviceSelect(obj) {
  delete queryForm.areaId;
  delete queryForm.managementStationId;
  delete queryForm.stationId;

  if(obj.type == 2){
    queryForm.areaId = obj.areaId;
  }else if(obj.type == 3){
    queryForm.managementStationId = obj.managementStationId
  }else if(obj.type == 4){
    queryForm.stationId = obj.stationId
  }
  queryFormState.pageNum = 1;
  queryData();
}

// 查询
function onSearch() {
  queryFormState.pageNum = 1;
  queryData();
}

// 切换分页
function onPageChange(pagination) {
  queryForm.pageNum = pagination.current;
  queryForm.pageSize = pagination.pageSize;
  queryData();
}

// 切换每页显示条数
function onShowSizeChange(pagination) {
  queryData();
}
// 查询数据
async function queryData() {
  queryForm.deviceTypeList = [queryForm.deviceType];
  tableLoading.value = true;
  try {
    let queryResult = await deviceApi.queryPumpAndGatePage(queryForm);
    tableData.value = queryResult.data.list;
    total.value = queryResult.data.total;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}

onMounted(() => {
  queryDict();
  orgTreeSelectionRef.value.getDepartmentList();
  queryData();
});

// ---------------------------- 查看运行日志 ----------------------------

const deviceRunningLogRef = ref();

function showDeviceRunningLog(data) {
  deviceRunningLogRef.value.show(data);
}


// ---------------------------- 添加/修改 ----------------------------
const formRef = ref();

function showForm(data) {
  formRef.value.show(data);
}

// ---------------------------- 单个删除 ----------------------------
//确认删除
function onDelete(data) {
  Modal.confirm({
    title: '提示',
    content: '确定要删除选吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      requestDelete(data);
    },
    cancelText: '取消',
    onCancel() {},
  });
}

//请求删除
async function requestDelete(data) {
  SmartLoading.show();
  try {
    let deleteForm = {
      goodsIdList: selectedRowKeyList.value,
    };
    let param =[];
    param.push(data.deviceId);
    await deviceApi.batchDelete(param);
    message.success('删除成功');
    queryData();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}

// ---------------------------- 批量删除 ----------------------------

// 选择表格行
const selectedRowKeyList = ref([]);

function onSelectChange(selectedRowKeys) {
  selectedRowKeyList.value = selectedRowKeys;
}

// 批量删除
function confirmBatchDelete() {
  Modal.confirm({
    title: '提示',
    content: '确定要批量删除这些数据吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      requestBatchDelete();
    },
    cancelText: '取消',
    onCancel() {},
  });
}

//请求批量删除
async function requestBatchDelete() {
  try {
    SmartLoading.show();
    await deviceApi.batchDelete(selectedRowKeyList.value);
    message.success('删除成功');
    queryData();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}
</script>
